<?php

namespace Biz\service\admin\tools;

use Encore\Admin\Layout\Content;
use Exception;
use Illuminate\Http\Request;

abstract class SimpleParseTpl
{

    protected static array $instance;
    protected Request $request;
    protected string $module;
    protected SimplePageTpl $tpl;
    protected SimpleRouteTpl $route;

    /**
     * @throws Exception
     */
    public static function getInstance($module, Request $request): SimpleParseTpl
    {
        if (empty(self::$instance[$module])) {
            $temp = new static();
            $temp->request = $request;
            $temp->module = $module;
            $temp->tpl = $temp->getTpl();
            $temp->route =  self::getRoute($module);
            self::$instance[$module] = $temp;
        }
        return self::$instance[$module];
    }



    public static function getRoute($module, $hasPid = false)
    {
        return SimpleRouteTpl::getRoute(static::getRoutePrefix(), $module, $hasPid);
    }

    /**
     * @throws Exception
     */
    public function getTpl(): SimplePageTpl
    {
        $class = static::CLASS_PREFIX . ucfirst($this->module);
        if (!class_exists($class)) throw new Exception("未找到配置文件,$class");
        $instance = new $class;
        if (!($instance instanceof SimplePageTpl)) throw new Exception("当前实例不符合规范");
        return $instance;
    }
    abstract public static function getRoutePrefix(): string;


    /**
     * 列表页
     */
    public function listDisplay(Content $content, $pid): Content
    {
        return $this->tpl->init($this->request, $pid)->listDisplay($content);
    }

    /**
     * 创建表单页
     */
    public function createDisplay(Content $content, $pid, $id): Content
    {
        session()->flash('info', false);
        return $this->tpl->init($this->request, $pid)->createDisplay($content, $id, $this->route);
    }

    /**
     * 创建表单页
     */
    public function exportDisplay($pid)
    {
        $this->tpl->init($this->request, $pid)->exportDisplay();
    }

    /**
     * 保存接口
     */
    public function saveApi($pid)
    {
        return $this->tpl->init($this->request, $pid)->saveApi($this->route);
    }

    /**
     * 快速保存接口
     */
    public function putApi($pid, $id): \Illuminate\Http\JsonResponse
    {
        return $this->tpl->init($this->request, $pid)->putApi($id);
    }

    /**
     * 删除接口
     */
    public function deleteApi($pid, $id): \Illuminate\Http\JsonResponse
    {
        return $this->tpl->init($this->request, $pid)->deleteApi($id);
    }

    /**
     * 排序接口
     */
    public function sortApi($pid)
    {
        $this->tpl->init($this->request, $pid)->sortApi();
    }
}